package com.candy.cms.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.candy.common.result.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.candy.cms.entity.Article;
import com.candy.cms.service.IArticleService;
import com.candy.common.controller.BaseController;
import io.swagger.annotations.Api;

import java.time.LocalDate;

/**
 * <p>
 * 文章 前端控制器
 * </p>
 *
 * @author pxs
 * @since 2021-06-27
 */
@Api(tags = "文章")
@RestController
@RequestMapping("/cms/article")
public class ArticleController extends BaseController<IArticleService, Article>
{

	@Override
	@ApiOperation(value = "新增")
	@PostMapping
	public R save(@Validated @RequestBody Article article)
	{
		if (article.getOrderNum() == null)
		{
			Integer maxOrderNum = baseService.getMaxOrderNum();
			if (maxOrderNum == null)
			{
				maxOrderNum = 0;
			}
			article.setOrderNum(++maxOrderNum);
		}
		if (article.getStatus() != null && article.getStatus() == 1 && StringUtils.isEmpty(article.getPulishTime()))
		{
			article.setPulishTime(LocalDate.now());
		}
		return R.success(baseService.save(article));
	}

	@Override
	@ApiOperation(value = "修改")
	@PutMapping
	public R edit(@Validated @RequestBody Article article)
	{
		if (article.getStatus() != null)
		{
			if (article.getStatus() == 0)
			{
				LambdaUpdateWrapper<Article> wrapper = new LambdaUpdateWrapper<>();
				wrapper.set(Article::getPulishTime, null);
				wrapper.eq(Article::getId, article.getId());
				baseService.update(wrapper);
			}
			else if (article.getStatus() == 1 && StringUtils.isEmpty(article.getPulishTime()))
			{
				Article oldArticle = baseService.getById(article.getId());
				if (oldArticle.getStatus() == null || oldArticle.getStatus() == 0)
				{
					article.setPulishTime(LocalDate.now());
				}
			}
		}
		return R.success(baseService.updateById(article));
	}
}
